package cs.upt.awp.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.AliasToBeanResultTransformer;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;

import cs.upt.awp.data.*;
import cs.upt.awp.model.TravelImageGalleryModel;

public class TravelImagesDAO implements DataDAO<TravelImage>{

	@Autowired
	SessionFactory sessionFactory;

	Session session = null;
	Transaction tx = null;    
	
	@Override
	public boolean addEntity(TravelImage entity) throws Exception {
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		session.save(entity);
		tx.commit();
		session.close();
		return false;
	}

	@Override
	public TravelImage getEntityById(long id) throws Exception {
		session = sessionFactory.openSession();
		TravelImage image = (TravelImage) session.load(TravelImage.class, new Long(id));
	//	session.close();
		return image;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TravelImage> getEntityList() throws Exception {
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		List<TravelImage> images = session.createCriteria(
				TravelImage.class).list();
		tx.commit();
		session.close();
		return images;
	}
	@SuppressWarnings("unchecked")
	public List<TravelImageGalleryModel> getImagesForRecord(long recordId){
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		List<TravelImageGalleryModel> images = session.createCriteria(
				TravelImage.class).add(Restrictions.eq("record.id", recordId)).setProjection(Projections.projectionList()
						.add(Projections.alias(Projections.property("title"), "title"))
						.add(Projections.alias(Projections.id(), "id") )
						.add(Projections.alias(Projections.property("description"),"description"))).setResultTransformer(Transformers.aliasToBean(TravelImageGalleryModel.class)).list();
		tx.commit();
		session.close();
		return images;
	}
	@Override
	public boolean deleteEntity(long id) throws Exception {
		session = sessionFactory.openSession();
		Object o = session.load(TravelImage.class, id);
		tx = session.getTransaction();
		session.beginTransaction();
		session.delete(o);
		tx.commit();
		session.close();
		return false;
	}



}

